import '@wangeditor/editor/dist/css/style.css' // 引入 css

import React, { useState, useEffect } from 'react'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import type {
  IDomEditor,
  IEditorConfig,
  IToolbarConfig
} from '@wangeditor/editor'

// 定义 props 的数据类型
interface MyEditorProps {
  onEditorChange: (newHtml: string) => void
  htmlContent?: string
}

function MyEditor(props: MyEditorProps) {
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null) // TS 语法

  // 编辑器内容
  const [html, setHtml] = useState('<p></p>')

  // 模拟 ajax 请求，异步设置 html
  useEffect(() => {
    // setTimeout(() => {
    //   setHtml('<p>hello world</p>')
    // }, 1500)
  }, [])

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {} // TS 语法

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    placeholder: '请输入内容...'
  }

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])

  useEffect(() => {
    if (props.htmlContent) {
      setHtml(props.htmlContent)
    }
  }, [props.htmlContent])

  const handleChange = (newHtml: string) => {
    // console.log('editor content change', newHtml)
    setHtml(newHtml)
    //子组件向父组件传递数据
    props.onEditorChange(newHtml)
  }
  return (
    <>
      <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="simple"
          style={{ borderBottom: '1px solid #ccc' }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={setEditor}
          onChange={(editor: IDomEditor) => {
            const newHtml = editor.getHtml()
            handleChange(newHtml)
          }}
          mode="simple"
          style={{ height: '300px', overflowY: 'hidden' }}
        />
      </div>
      {/* <div style={{ marginTop: '15px' }}>{html}</div> */}
    </>
  )
}

export default MyEditor
